// +----------------------------------------------------------------------
// | BossHongshi [鸿时互娱管理系统]
// +----------------------------------------------------------------------
// | Copyright (c) 2018 http://www.hongshihuyu.com All rights reserved.
// +----------------------------------------------------------------------
// | Author: wgh
// +----------------------------------------------------------------------
// const pingpp = require('pingpp');
var urlencode = require('urlencode');
const API = require('co-wechat-api');
const fs = require('fs');
const fly=require("flyio");
const superagent = require('superagent');
module.exports = class extends think.cmswing.center {
  constructor(ctx) {
    super(ctx); // 调用父级的 constructor 方法，并把 ctx 传递进去
    // 其他额外的操作
    // this.api = new API(this.config('setup.wx_AppID'), this.config('setup.wx_AppSecret'));
    this.api = new API(this.config('setup.wx_AppID'), this.config('setup.wx_AppSecret'), async function() {
      // 传入一个获取全局token的方法
      try {
        const fn = think.promisify(fs.readFile, fs);
        const txt = await fn(think.ROOT_PATH + '/private/access_token.txt');
        return JSON.parse(txt);
      } catch (e) {
        return null;
      }
    }, async function(token) {
      // 请将token存储到全局，跨进程、跨机器级别的全局，比如写到数据库、redis等
      // 这样才能在cluster模式及多机情况下使用，以下为写入到文件的示例
      const fns = think.promisify(fs.writeFile, fs);
      await fns(think.ROOT_PATH + '/private/access_token.txt', JSON.stringify(token));
    });
  }

  /**
     * index action
     * @return {Promise} []
     */
  indexAction() {
    // auto render template file index_index.html
    return this.display();
  }
  async oauthAction() {
    // 判断是否是微信浏览器
    // 微信公众账号内自动登陆
    let openid = await this.session('wx_openid');
    const invid = this.para('i') || null;//邀请人代理ID
    const type = this.para('t') || null;//1:邀请代理;2:下载拉新；3:加入房间
    const room = this.para('r') || null;//房间号
    const channel = this.para('c') || null;//渠道
    const mwin = this.para('m') || null;//魔窗
//    console.log('oauth invid 1------------------:'+invid);
//    console.log('oauth type 1------------------:'+type);
//    console.log('oauth room 1------------------:'+room);
//    console.log('oauth channel 1------------------:'+channel);
//    console.log('oauth mwin 1------------------:'+mwin);
//    console.log("oauth session wx_openid ---:"+openid);
    openid = null;
    if(!think.isEmpty(type)&&type==3){
       this.redirect('/center/weixin/room?invid='+invid+'&type='+type+'&room='+room+'&channel='+channel+'&mwin='+mwin);
    }else{
      if(this.isweixin && think.isEmpty(openid)) {
         this.cookie('cmswing_wx_url', this.ctx.url);
         const pingpp = require('pingpp')(this.config('setup.wx_AppSecret'));
         var redirect_uri ='http://www.hongshihuyu.com/center/weixin/getopenid?showwxpaytitle=1&invid='+invid+'&type='+type+'&room='+room+'&channel='+channel;
         console.log("redirect_uri ---:"+redirect_uri);
         //console.log("urlencode---:"+urlencode(redirect_uri));
         const oauthUrl = "https://open.weixin.qq.com/connect/oauth2/authorize?appid="+this.config('setup.wx_AppID')+"&redirect_uri="+urlencode(redirect_uri)+"&response_type=code&scope=snsapi_userinfo&state=1#wechat_redirect";
         console.log("oauthUrl---:"+oauthUrl);
         return this.redirect(oauthUrl);
      }else{
        this.redirect('/center/weixin/down');
      }
    }
  }
  // 用微信客户端获取getopenid
  async getopenidAction() {
    const pingpp = require('pingpp')(this.config('setup.wx_AppSecret'));
    // 获取用户openid
    const code = this.get('code');
//    console.log("getopenid code---:"+code);
    const invid = this.para('invid') || null;//i 当t为1时，传邀请人代理ID；当t为2时，传分享下载人的游戏uid；当t为3时，传分享房间人的游戏uid；
    const type = this.para('type') || null;//1:邀请代理;2:下载拉新；3:加入房间
    const room = this.para('room') || null;//房间号
    const channel = this.para('channel') || null;//渠道

//    console.log('getopenid invid 3------------------:'+invid);
//    console.log('getopenid type 3------------------:'+type);
//    console.log('getopenid room 3------------------:'+room);
//    console.log('getopenid channel 3------------------:'+channel);

    fly.config.timeout=10000;
	fly.config.parseJson=true;
	fly.interceptors.response.use(
		 (response) => {
						        //只将请求结果的data字段返回
			return response.data
		 },
		 (err) => {
				//发生网络错误后会走到这里
				//return Promise.resolve("ssss")
		 }
    )
    
    let access_token_url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid="+this.config('setup.wx_AppID')+"&secret="+this.config('setup.wx_AppSecret')+"&code="+code+"&grant_type=authorization_code";
    let access_token_ret = await fly.get(access_token_url).catch(() => false);
    console.log("access_token_ret---:"+access_token_ret);
    let access_token_retjson = (access_token_ret === false?null:JSON.parse(access_token_ret));
    //console.log("access_token_ret---:"+JSON.stringify(access_token_ret));
    console.log("access_token---:"+access_token_retjson.access_token);

    let userinfo_url = "https://api.weixin.qq.com/sns/userinfo?access_token="+access_token_retjson.access_token+"&openid="+access_token_retjson.openid+"&lang=zh_CN";
    let userinfo_ret = await fly.get(userinfo_url).catch(() => false);
    console.log("userinfo_ret---:"+userinfo_ret);
    let userinfo_retjson = (userinfo_ret === false?null:JSON.parse(userinfo_ret));
    
    //const openid = access_token_retjson.openid;
    //console.log("openid--------:"+openid);
    const unionid = userinfo_retjson.unionid;
    console.log("unionid--------:"+unionid);

    //const userinfo = await this.api.getUser(openid);
    // console.log("userinfo---:"+JSON.stringify(userinfo));

    // var uid=0;
    // var proxy_id=0;
    if(!think.isEmpty(type)){
      // if(type==2){
      //   uid=invid;
      // }else if(type==1){
      //   proxy_id=invid;
      // }
    	
    let playerinfo_url = "http://47.97.119.70:5166/GameSupport/dn?cmd=register&openid="
    +userinfo_retjson.openid
    +"&nickname="+userinfo_retjson.nickname
    +"&fromUid="+invid
    +"&sex="+userinfo_retjson.sex
    +"&province="+userinfo_retjson.province
    +"&city="+userinfo_retjson.city
    +"&country="+userinfo_retjson.country
    +"&headimgurl="+userinfo_retjson.headimgurl
    +"&unionid="+userinfo_retjson.unionid
    +"&channel="+channel
    +"&sign=password";
    console.log("playerinfo_url---:"+playerinfo_url);
    let playerinfo_ret = await fly.get(encodeURI(playerinfo_url)).catch(() => false);
    console.log("playerinfo_ret---:"+playerinfo_ret);
    let playerinfo_retjson = (playerinfo_ret === false?null:JSON.parse(playerinfo_ret));
    /**
    if(playerinfo_retjson.data.result==0){
       const memberInfo = await this.model('member').where({game_id: invid}).find();
       let bindByUnionId_url ="http://47.97.119.70:5166/GameSupport/dn?cmd=bindByUnionId&unionId="
    	   +playerinfo_retjson.data.info.unionid+"&agentId="+memberInfo.proxy_id+"&sign=password";
       console.log("bindByUnionId_url---:"+bindByUnionId_url);
       let bindByUnionId_ret = await fly.get(bindByUnionId_url).catch(() => false);
       console.log("bindByUnionId_ret---:"+bindByUnionId_ret);
    }else {
      	if(think.isEmpty(playerinfo_retjson.data.info.parent_id)){
      		const memberInfo = await this.model('member').where({game_id: invid}).find();
            let bindByUnionId_url ="http://47.97.119.70:5166/GameSupport/dn?cmd=bindByUnionId&unionId="
         	   +playerinfo_retjson.data.info.unionid+"&agentId="+memberInfo.proxy_id+"&sign=password";
            console.log("bindByUnionId_url---:"+bindByUnionId_url);
            let bindByUnionId_ret = await fly.get(bindByUnionId_url).catch(() => false);
            console.log("bindByUnionId_ret---:"+bindByUnionId_ret);
      	}
    }
    */
  }
  this.redirect('/center/weixin/down');
}

  /**
     * 没有关注提示关注
     */
  async followAction() {
    // console.log(this.setup)
    // 创建关注二维码
    // TODO
    //let titck =await createLimitQRCode(this.api,1);
    //console.log("titck---:"+titck);
    //const qrcod = this.api.showQRCodeURL('gQHz7zoAAAAAAAAAASxodHRwOi8vd2VpeGluLnFxLmNvbS9xL3JqX0p2Zm5sMnBtalQwX215eE1NAAIEjMBoVwMEAAAAAA==');
    //this.assign('qrurl', qrcod);
    // think.log(qrcod);
    // this.end(qrcod);
    this.meta_title = `扫码关注`;
    // 判断浏览客户端
    if (this.isMobile) {
      return this.display(this.mtpl());
    } else {
      return this.display(this.mtpl());
    }
  }

    /**
     * 微信账号与网站会员绑定
     */
  async downAction() {
    // todo
    this.assign('random', Math.random());
    if (this.isMobile) {
      return this.display(this.mtpl());
    } else {
      return this.display();
    }
    // this.end("网站会员绑定页面")
  }

    async roomAction() {
    // todo
    //invid='+invid'&type='+type+'&room='+room+'&channel='+channel+'&mwin='+mwin
    const invid = this.para('invid') || null;//邀请人代理ID
    const type = this.para('type') || null;//1:邀请代理;2:下载拉新；3:加入房间
    const room = this.para('room') || null;//房间号
    const channel = this.para('channel') || null;//渠道
    const mwin = this.para('mwin') || null;//魔窗

    console.log('oauth invid 2------------------:'+invid);
    console.log('oauth type 2------------------:'+type);
    console.log('oauth room 2------------------:'+room);
    console.log('oauth channel 2------------------:'+channel);
    console.log('oauth mwin 2------------------:'+mwin);
  
    //var puserinfo = await this.session('puserinfo');
    fly.config.timeout=10000;
	fly.config.parseJson=true;
	fly.interceptors.response.use(
		 (response) => {
						        //只将请求结果的data字段返回
			return response.data
		 },
		 (err) => {
				//发生网络错误后会走到这里
				//return Promise.resolve("ssss")
		 }
    )
    
    let pu_url = "http://47.97.119.70:5166/GameSupport/dn?cmd=getPlayerByUid&uid="+invid+"&sign=password";
    let pu_ret = await fly.get(pu_url).catch(() => false);
    console.log("pu_ret---:"+pu_ret);
    let pu_retjson = (pu_ret === false?null:JSON.parse(pu_ret));
    console.log("pu_retjson---:"+JSON.stringify(pu_retjson));
    
    let room_url = "http://47.97.119.70:5166/GameSupport/dn?cmd=getRoomById&roomId="+room+"&sign=password";
    let room_ret = await fly.get(room_url).catch(() => false);
    console.log("room_ret---:"+room_ret);
    let room_retjson = (room_ret === false?null:JSON.parse(room_ret));
    console.log("room_retjson---:"+JSON.stringify(room_retjson));
	 console.log("roominfo---:"+JSON.stringify(room_retjson.data.info));
	this.assign('room', room);
	this.assign('puserinfo', pu_retjson.data.info);
    this.assign('roominfo', think.isEmpty(room_retjson.data.info)?null:room_retjson.data.info);
    this.assign('mwin', mwin);
    this.assign('random', Math.random());
    if (this.isMobile) {
      return this.display(this.mtpl());
    } else {
      return this.display();
    }
    // this.end("网站会员绑定页面")
  }

  /**
     * 微信账号与网站会员绑定
     */
  async signinAction() {
    // await this.session('wx_openid',"o33lBt0Pz3rEXUARWtUUO5GxuUG0");
    let open_id;
    if (think.isEmpty(this.cookie('wx_openid'))) {
      open_id = await this.session('wx_openid');
      this.cookie('wx_openid', open_id);
    } else {
      open_id = this.cookie('wx_openid');
    }

    // 清除openid，如果中途失败，可重新激活注册流程
    await this.session('wx_openid', null);
    const wx_info = await this.model('wx_user').where({openid: open_id}).find();
    this.assign('wx_info', wx_info);
    this.meta_title = '账号绑定';
    this.assign('openid', open_id);
    this.assign('headimgurl', wx_info.headimgurl);
    // todo
    if (this.isMobile) {
      return this.display(this.mtpl());
    } else {
      return this.display();
    }
    // this.end("网站会员绑定页面")
  }
  /** 完善资料绑定 */
  async organizingAction() {
    const data = this.post();
    // 验证
    let res;
    if (think.isEmpty(data.username)) {
      return this.fail('用户昵称不能为空！');
    } else {
      res = await this.model('member').where({username: ltrim(data.username)}).find();
      if (!think.isEmpty(res)) {
        return this.fail('用户昵称已存在，请重新填写！');
      }
    }
    if (think.isEmpty(data.mobile)) {
      return this.fail('手机号码不能为空！');
    } else {
      res = await this.model('member').where({mobile: data.mobile}).find();
      if (!think.isEmpty(res)) {
        return this.fail('手机号码已存在，请重新填写！');
      }
    }
    if (think.isEmpty(data.email)) {
      return this.fail('电子邮箱不能为空！');
    } else {
      res = await this.model('member').where({email: data.email}).find();
      if (!think.isEmpty(res)) {
        return this.fail('电子邮箱已存在，请重新填写！');
      }
    }
    if (think.isEmpty(data.password) && think.isEmpty(data.password2)) {
      return this.fail('密码不能为空！');
    } else {
      if (data.password != data.password2) {
        return this.fail('两次输入的密码不一致，请重新填写！');
      }
    }
    data.status = 1;
    data.reg_time = new Date().valueOf();
    data.reg_ip = _ip2int(this.ip);
    data.password = encryptPassword(data.password);
    const reg = await this.model('member').add(data);

    if (!think.isEmpty(reg)) {
      // 用户副表
      await this.model('wx_user').where({openid: data.openid}).update({uid: reg});
      // 更新微信头像
      const filePath = think.resource + '/upload/avatar/' + reg;
      think.mkdir(filePath);
      await this.spiderImage(data.headimgurl, filePath + '/avatar.png');
    }
    console.log(data);
    await this.model('cmswing/member').autoLogin({id: reg}, this.ip);// 更新用户登录信息，自动登陆
    const wx_userInfo = {
      'uid': reg,
      'username': data.username,
      'last_login_time': data.reg_time
    };
    await this.session('webuser', wx_userInfo);
    // 成功后储存opid,防止无限登陆
    await this.session('wx_openid', data.openid);
    this.cookie('wx_openid', null);
    return this.success({name: '绑定成功', url: '/center/index'});
  }
  /** 登录绑定 */
  async logonbindingAction() {
    const data = this.post();
    const username = this.post('username');
    let password = this.post('password');
    password = encryptPassword(password);
    console.log(data);

    const res = await this.model('cmswing/member').signin(username, password, this.ip, 5, 0);
    if (res.uid > 0) {
      // 记录用户登录行为
      // await this.model("action",).log("user_login", "member", res.uid, res.uid, this.ip(), this.http.url);
      // console.log(11111111111111);
      const wx_info = await this.model('wx_user').where({openid: data.openid}).find();
      await this.model('wx_user').where({openid: data.openid}).update({uid: res.uid});
      // 更新微信头像
      const filePath = think.resource + '/upload/avatar/' + res.uid;
      think.mkdir(filePath);
      await this.spiderImage(data.headimgurl, filePath + '/avatar.png');
      res.username = wx_info.nickname;
      await this.session('webuser', res);
      // 成功后储存opid,防止无限登陆
      await this.session('wx_openid', data.openid);
      this.cookie('wx_openid', null);
      // TODO 用户密钥
      return this.success({name: '绑定成功', url: '/center/index'});
    } else { // 登录失败
      let fail;
      switch (res) {
        case -1:
          fail = '用户不存在或被禁用';
          break; // 系统级别禁用
        case -2:
          fail = '密码错误';
          break;
        default:
          fail = '未知错误';
          break; // 0-接口参数错误（调试阶段使用）
      }
      this.fail(fail);
    }
  }
  /**
   * 更新微信头像
  */
  spiderImage(imgUrl, filePath) {
    const deferred = think.defer();
    superagent
      .get(imgUrl) // 这里的URL也可以是绝对路径
      .end(function(req, res) {
        // console.log(filePath);
        // console.log(res.body);
        fs.writeFileSync(filePath, res.body);
        deferred.resolve(filePath);
      });
    return deferred.promise;
  }
};
